/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package web.util;

/**
 *
 * @author kabad
 */
import java.sql.SQLException;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;

import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.lang.annotation.Annotation;
import java.util.Properties;
import javax.annotation.Resource;
import javax.naming.Context;

public class SendMail {

    @Resource(name = "mail/MailFiec", type = Session.class)
    private Session mailSession;
    private String from;
    private String to;
    private String subject;
    private String text;

    public SendMail(String to, String subject, String text) throws SQLException {
        this.to = to;
        this.subject = subject;
        this.text = text;
        this.from = from;
    }

    public void send() throws NamingException, AddressException, MessagingException {
        System.out.println("mailSession    " + mailSession);
//            InitialContext ic = new InitialContext();
//            String snName = "java:comp/env/mail/MailFiec";
//             mailSession = (Session) ic.lookup(snName);
        Properties props = new Properties();
        props.put("mail.smtp.host", "ceibo.fiec.espol.edu.ec");
            props.put("mail.smtp.user", "kabad@fiec.espol.edu.ec");
//            Authenticator auth = new MiAutenticador();
        mailSession = Session.getInstance(props);
        InternetAddress fromAddress = null;
        InternetAddress toAddress = null;

        fromAddress = new InternetAddress("kabad@fiec.espol.edu.ec");
        toAddress = new InternetAddress(to);
        Message simpleMessage = new MimeMessage(mailSession);
        simpleMessage.setFrom(fromAddress);
//        simpleMessage.setFrom();
        simpleMessage.setRecipient(RecipientType.TO, toAddress);
        simpleMessage.setSubject(subject);
        simpleMessage.setText(text);
        Transport.send(simpleMessage);
    }

    private static class MiAutenticador extends Authenticator {

        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("kabad@fiec.espol.edu.ec", "fiec1984");
        }
    }
}
